package com.shwread.android.qysw.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.shwread.android.qysw10000136.R;
import com.shwread.android.ui.dialog.BookTicketActivateDialog;
import com.shwread.android.ui.dialog.NetworkDialog;
import com.shwread.android.ui.dialog.SimpleListener;
import com.shwread.httpsdk.http.callback.ActionListener;
import com.shwread.httpsdk.http.face.ActivateEcardAction;
import com.shwread.httpsdk.http.face.CheckEcardAction;
import com.shwread.httpsdk.util.DESUtil;
import logic.beanenum.Ecard_Enum;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.util.NetworkUtil;
import logic.util.Util;


/**
 * @Project： Shwread
 * @Title：BookTicketActivity
 * @Description：激活界面
 * @Author：wayne
 * @Date：2014年11月18日上午11:43:47
 */
public class BookTicketActivity
        extends
        BaseBusinessActivity
        implements
        OnClickListener
{
	private Context                  mContext;
	private Button                   btnEnsure, btnBack;
	private TextView                 tvTitle;
	private EditText                 etCardNumber, etCardPwd;
	//	private AutoCompleteTextView tvAccount;
	//	private ImageView ivAccountMore,ivAccountClear;
	//	private View vAccount,vAccountTxt;
	//	private PopupWindow moreAccountPup;
	//	private List<UserBean>            users;
	private ImageView                ivCardNumberClear, ivCardPwdClear;
	private int                      fromType;
	private boolean                  mbDisplayFlg = false;
	
	private BookTicketActivateDialog dialog;
	@SuppressLint ("HandlerLeak")
	private Handler                  myHandler    = new Handler()
	                                              {
		                                              @Override
		                                              public void handleMessage(Message msg) {
			                                              switch (msg.what) {
														  }
													  }
	                                              };
	public int                       resultCode;
	public String                    message;
	//	public String currAccount;
	private String                   cardNum;
	private String                   cardPwd;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.book_ticket_activate);
		mContext = this;
		
		Bundle bundle = getIntent().getExtras();
		if (null != bundle)
		{
			fromType = bundle.getInt(DefaultConsts.from_page);
		}
		
		initView();
		//		initData();
		setLinstener();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
	}
	
	private class FocusChangeListener
	        implements
	        OnFocusChangeListener
	{
		View     view;
		EditText et;
		
		public FocusChangeListener(EditText et, View view) {
			this.view = view;
			this.et = et;
		}
		
		@Override
		public void onFocusChange(View arg0, boolean arg1) {
			boolean value = arg1 && Util.isNotEmpty(et.getText().toString().trim());
			view.setVisibility(value ? View.VISIBLE : View.GONE);
		}
	}
	
	private void initView() {
		btnBack = (Button) findViewById(R.id.common_header_back);
		tvTitle = (TextView) findViewById(R.id.common_header_name);
		btnEnsure = (Button) findViewById(R.id.book_ticket_activate_ensure_btn);
		etCardNumber = (EditText) findViewById(R.id.book_ticket_activate_card_number_et);
		etCardPwd = (EditText) findViewById(R.id.book_ticket_activate_card_pwd_et);
		ivCardNumberClear = (ImageView) findViewById(R.id.book_ticket_activate_card_number_clear_iv);
		ivCardPwdClear = (ImageView) findViewById(R.id.book_ticket_activate_card_pwd_clear_iv);
		//		tvAccount = (AutoCompleteTextView) findViewById(R.id.book_ticket_activate_account_tv);
		//		ivAccountMore = (ImageView) findViewById(R.id.book_ticket_activate_account_more_iv);
		//		ivAccountClear = (ImageView) findViewById(R.id.book_ticket_activate_account_clear_iv);
		//		vAccount = findViewById(R.id.book_ticket_activate_account_ll);
		//		vAccountTxt = findViewById(R.id.book_ticket_activate_card_number_txt3);
		
		if (!mbDisplayFlg)
		{
			// display password text, for example "123456" 
			etCardPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
		}
		else
		{
			// hide password, display "."
			etCardPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
		}
		if (fromType == DefaultConsts.TAG_BOOKSHELF)
		{
			btnEnsure.setText("激活");
		}
		else
		{
			
			btnEnsure.setText("下一步");
		}
		btnBack.setVisibility(View.VISIBLE);
		tvTitle.setText("服务续约");
	}
	
	//	private class ItemClick implements OnItemClickListener{
	//		@Override
	//        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
	//			tvAccount.setText(users.get(arg2).getAccount());
	//			moreAccountPup.dismiss();
	//        }
	//	}
	//	void initDropPop() {
	//		Util.hideInputMethodManager(mContext,tvAccount);
	//		final View view =  new PopupWindowUtil(mContext, users, new ItemClick()).getView();
	//		final int width = vAccount.getWidth()-vAccountTxt.getWidth();
	//		moreAccountPup = new PopupWindow(view, width, LayoutParams.WRAP_CONTENT);
	//		moreAccountPup.setBackgroundDrawable(new BitmapDrawable());
	//		moreAccountPup.setFocusable(true);
	//		moreAccountPup.showAsDropDown(tvAccount, 0, 0);
	//	}
	@Override
	protected void onDestroy() {
		System.out.println("");
		super.onDestroy();
	}
	
	//	private void initData() {
	//		if(DefaultConsts.TAG_PERSONAL==fromType){
	//			tvAccount.setText(Util.isEmpty(Const.phone_number)?"":Const.phone_number);
	//			ivAccountClear.setVisibility(Util.isEmpty(Const.phone_number)?View.GONE:View.VISIBLE);
	//			ivAccountMore.setVisibility(View.GONE);
	//			return;
	//		}
	//		users = UserDao.getInstance(mContext).getAllUser();
	//		if (null==users || users.isEmpty())
	//		{
	//			tvAccount.setText("");
	//			ivAccountMore.setVisibility(View.GONE);
	//		}
	//		else
	//		{
	//			final UserBean user = UserDao.getInstance(mContext).getLastLoginUser();
	//			tvAccount.setText(user.getAccount());
	//			ivAccountMore.setVisibility(View.VISIBLE);
	//		}
	//	}
	
	private void setLinstener() {
		btnBack.setOnClickListener(this);
		btnEnsure.setOnClickListener(this);
		ivCardNumberClear.setOnClickListener(this);
		ivCardPwdClear.setOnClickListener(this);
		etCardNumber.addTextChangedListener(new TextChangedListener(ivCardNumberClear));
		etCardPwd.addTextChangedListener(new TextChangedListener(ivCardPwdClear));
		
		//		ivAccountMore.setOnClickListener(this);
		//		ivAccountClear.setOnClickListener(this);
		//		tvAccount.addTextChangedListener(new TextChangedListener(ivAccountClear));
		//		tvAccount.setOnFocusChangeListener(new FocusChangeListener(tvAccount,ivAccountClear));
		etCardNumber.setOnFocusChangeListener(new FocusChangeListener(etCardNumber, ivCardNumberClear));
		etCardPwd.setOnFocusChangeListener(new FocusChangeListener(etCardPwd, ivCardPwdClear));
	}
	
	private void clickEnsure() {
		if (NetworkUtil.isNetAvailable(this))
		{
			check();
		}
		else
		{
			new NetworkDialog(this).show();
		}
	}
	
	@Override
	public Handler getUIHandler() {
		return myHandler;
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK)
		{
			if (fromType == DefaultConsts.TAG_LOGIN)
			{
				startActivity(new Intent(this, NewLoginActivity.class));
			}
			BookTicketActivity.this.finish();
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.common_header_back:
				if (fromType == DefaultConsts.TAG_LOGIN)
				{
					startActivity(new Intent(this, NewLoginActivity.class));
				}
				BookTicketActivity.this.finish();
				break;
			case R.id.book_ticket_activate_ensure_btn:
				clickEnsure();
				break;
			//			case R.id.book_ticket_activate_account_more_iv:
			//				initDropPop();
			//				break;
			case R.id.book_ticket_activate_card_number_clear_iv:
				etCardNumber.setText("");
				ivCardNumberClear.setVisibility(View.GONE);
				etCardPwd.setText("");
				ivCardPwdClear.setVisibility(View.GONE);
				break;
			case R.id.book_ticket_activate_card_pwd_clear_iv:
				etCardPwd.setText("");
				ivCardPwdClear.setVisibility(View.GONE);
				break;
		//			case R.id.book_ticket_activate_account_clear_iv:
		//				tvAccount.setText("");
		//				ivAccountClear.setVisibility(View.GONE);
		//				break;
		}
	}
	
	private void setEnable(boolean enabled) {
		//		tvAccount.setEnabled(enabled);
		//		ivAccountMore.setEnabled(enabled);
		etCardNumber.setEnabled(enabled);
		etCardPwd.setEnabled(enabled);
		ivCardNumberClear.setEnabled(enabled);
		ivCardNumberClear.setEnabled(enabled);
		btnEnsure.setEnabled(enabled);
		//		btnEnsure.setText(enabled ? "激活" : "激活中...");
	}
	
	void check() {
		//		String account = tvAccount.getText().toString().trim();
		cardNum = etCardNumber.getText().toString().trim();
		cardPwd = etCardPwd.getText().toString().trim();
		
		//		if (Util.isEmpty(account))
		//		{
		//			Util.showToast(mContext, "请输入帐号");
		//		}else if(!Util.isMobile(account)){
		//			Util.showToast(mContext, "建议输入手机号享受更多服务哦");
		//		}
		//		else 
		if (Util.isEmpty(cardNum))
		{
			Util.showToast(mContext, "请输入书券上的卡号");
		}
		else if (Util.isEmpty(cardPwd))
		{
			Util.showToast(mContext, "请输入书券上的密码");
		}
		else
		{
			setEnable(false);
			if (DefaultConsts.TAG_LOGIN == fromType) //未登录
			{
				new CheckEcardAction(mContext, "", cardNum, cardPwd, "0", new MActionListener()).start();
			}
			else
			//已登录
			{
				new CheckEcardAction(mContext, Const.phone_number, cardNum, cardPwd, "1", new MActionListener()).start();
			}
			//			if (DefaultConsts.TAG_LOGIN==fromType)
			//			{
			//				new ActivateEcardAction(mContext, account, cardNum, cardPwd, Ecard_Enum.ACTIVATE.getValue(), "0", "", new MActionListener()).start();
			//			}
			//			else
			//			{
			//				if (Const.phone_number.equals(account))
			//				{
			//					new ActivateEcardAction(mContext, account, cardNum, cardPwd, Ecard_Enum.ACTIVATE.getValue(), "1", "", new MActionListener()).start();
			//				}
			//				else
			//				{
			//					new ActivateEcardAction(mContext, Const.phone_number, cardNum, cardPwd, Ecard_Enum.GIVE.getValue(), "1", account, new MActionListener()).start();
			//				}
			//				
			//			}
		}
	}
	
	class MActionListener
	        implements
	        ActionListener
	{
		
		@Override
		public void OK(Object obj) {
			myHandler.post(new Runnable()
			{
				@Override
				public void run() {
					setEnable(true);
					activationFinish();
				}
			});
		}
		
		@Override
		public void ERROR(final int code, final String msg) {
			resultCode = code;
			message = msg;
			myHandler.post(new Runnable()
			{
				@Override
				public void run() {
					setEnable(true);
					if (code == 2100)
					{//电子券信息错误,这个也需要显示dialog,待测试
						showDialog();
					}
					else
					{
						Util.showToast(mContext, message);
					}
				}
			});
		}
		
		@Override
		public void HTTPERROR(int statusCode) {
			myHandler.post(new Runnable()
			{
				@Override
				public void run() {
					setEnable(true);
					Util.showToast(mContext, "请求超时，请重试！");
				}
			});
		}
	}
	
	class ActiveActionListener
	        implements
	        ActionListener
	{
		
		@Override
		public void OK(final Object obj) {
			myHandler.post(new Runnable()
			{
				@Override
				public void run() {
					showDialog(true, obj.toString());
				}
			});
		}
		
		@Override
		public void ERROR(final int code, final String msg) {
			myHandler.post(new Runnable()
			{
				@Override
				public void run() {
					if (code == 2100)
					{//电子券信息错误,这个也需要显示dialog,待测试
						showDialog(false, msg);
					}
					else
					{
						Util.showToast(BookTicketActivity.this, msg);
					}
				}
			});
		}
		
		@Override
		public void HTTPERROR(int statusCode) {
			myHandler.post(new Runnable()
			{
				@Override
				public void run() {
					Util.showToast(BookTicketActivity.this, "请求超时，请重试！");
				}
			});
		}
	}
	
	private void showDialog(boolean isSuccess, String message) {
		new BookTicketActivateDialog(this, isSuccess, message, new DialogListener()).show();
	}
	
	private class DialogListener
	        implements
	        SimpleListener
	{
		@Override
		public void ok() {
			finish();
		}
	}
	
	private class TextChangedListener
	        implements
	        TextWatcher
	{
		View view;
		
		public TextChangedListener(View view) {
			this.view = view;
		}
		
		@Override
		public void afterTextChanged(Editable arg0) {
		}
		
		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
		}
		
		@Override
		public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
			view.setVisibility(Util.isEmpty(s.toString()) ? View.GONE : View.VISIBLE);
		}
	}
	
	/** 电子券激活完成的操作 */
	private void activationFinish() {
		//电子券激活信息错误时不跳转
		if (fromType == DefaultConsts.TAG_LOGIN || fromType == DefaultConsts.TAG_PERSONAL)
		{
			Intent intent = new Intent(mContext, LoginAfterBookTicketActivateActivity.class);
			String num = "", pwd = "";
			try
			{
				num = DESUtil.encrypt(cardNum);
				pwd = DESUtil.encrypt(cardPwd);
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			
			intent.putExtra(DefaultConsts.FROM_TYPE, fromType);
			intent.putExtra(DefaultConsts.CURR_CARD, num);
			intent.putExtra(DefaultConsts.CURR_PASSWORD, pwd);
			startActivity(intent);
		}
		else if (fromType == DefaultConsts.TAG_BOOKSHELF)
		{
			//书架立即续订，不需要绑定帐号，直接调激活接口
			new ActivateEcardAction(this, Const.phone_number, cardNum, cardPwd, Ecard_Enum.ACTIVATE.getValue(), "1", "", "", new ActiveActionListener()).start();
		}
	}
	
	private void showDialog() {
		if (dialog != null)
		{
			if (dialog.isShowing()) dialog.dismiss();
			dialog = null;
		}
		dialog = new BookTicketActivateDialog(mContext, false, message, null);
		dialog.show();
	}
	
}
